package org.jivesoftware.sparkimpl.plugin.transcripts;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import javax.swing.JEditorPane;

import org.jdesktop.swingx.calendar.DateUtils;
import org.jivesoftware.resource.Res;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;

/**
 * 用于管理所有的历史消息操作
 * 
 * @author SidneyRen
 *
 */
public class HistoryMessageManager {

	private final String timeFormat = ((SimpleDateFormat) SimpleDateFormat
			.getDateInstance(SimpleDateFormat.SHORT)).toPattern();
	
	private final String dateFormat = ((SimpleDateFormat) SimpleDateFormat
			.getDateInstance(SimpleDateFormat.FULL)).toPattern();
	
	private final SimpleDateFormat notificationDateFormatter;
	private final SimpleDateFormat messageDateFormatter;
	private static DateFormat FORMATTER;
	private HistoryMessagePanel messageHistoryPanel;
	private static HistoryMessageManager instance;
	private final LocalPreferences pref = SettingsManager.getLocalPreferences();
	private final SimpleDateFormat messageTimeFormatter ;

	static {
		FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
	}
	
	public static HistoryMessageManager getInstance() {
		if(null==instance)	
			instance = new HistoryMessageManager();
		return instance;
	}
	
	private HistoryMessageManager() {
		//TODO
		notificationDateFormatter = new SimpleDateFormat(dateFormat);
		messageDateFormatter = new SimpleDateFormat(timeFormat);
		messageTimeFormatter= new SimpleDateFormat(pref.getTimeFormat());
	}
	
	/**
	 * 创建历史消息面板
	 * 
	 * @param title
	 * @return
	 */
	public HistoryMessagePanel getHistoryMessagePanel(String title){
		return new HistoryMessagePanel(title,false);
	}
	
	public HistoryMessagePanel getHistoryMessagePanel(String title,boolean isChinaGroup){
		return new HistoryMessagePanel(title,isChinaGroup);
	}
		
	public void showBroadcastHistory(String filename) {
		showOnPanel(filename, null,getHistoryMessagePanel(filename),false);
	}

	public void showTranscript(String jid) {
		showOnPanel(jid, null,getHistoryMessagePanel(jid),false);
	}
	
	public void showTranscript(String jid,boolean isChinaGroup) {
		showOnPanel(jid, null,getHistoryMessagePanel(jid,isChinaGroup),isChinaGroup);
	}
	
	public void showSearchResult(String title,Date date,final HistoryMessagePanel messageHistoryPanel,boolean isChinaGroup){
		showOnPanel(title, date, messageHistoryPanel,isChinaGroup);
	}
	
	public void showOnPanel(final String title,final Date date,final HistoryMessagePanel messageHistoryPanel,final boolean isChinaGroup) {
		
		SwingWorker transcriptLoader = new SwingWorker() {
			public Object construct() {
				//TODO 
				String bareJID = StringUtils.parseBareAddress(title);
				//Test
				return ChatTranscripts.getChatTranscript(bareJID);
			}

			public void finished() {
				
				final JEditorPane window = messageHistoryPanel.getTranscriptPane();
				messageHistoryPanel.setAllTitle(title);
				final ChatTranscript transcript = (ChatTranscript) get();
				final List<HistoryMessage> list = transcript.getMessages();
				final String personalNickname = SparkManager.getUserManager()
						.getNickname();
				
//				final List<HistoryMessage> tempList = new ArrayList<HistoryMessage>();
				final List<HistoryMessage> tempList = new ArrayList<HistoryMessage>(list);
				if(null!=date){
					tempList.clear();
					for(HistoryMessage message : list){
						String messageDate = messageDateFormatter.format(message.getDate());
						String queryDate = messageDateFormatter.format(date);
//						if(0==DateUtils.getDaysDiff(date.getTime(),message.getDate().getTime())){
//							tempList.add(message);
//						}
						if(queryDate.equals(messageDate)){
							tempList.add(message);
						}
					}
				}else {
					
//					HistoryMessage lastMessage = list.get(list.size()-1);
//					for(HistoryMessage message : list){
//						if(0==DateUtils.getDaysDiff(lastMessage.getDate().getTime(),message.getDate().getTime())||1==DateUtils.getDaysDiff(lastMessage.getDate().getTime(),message.getDate().getTime())){
//							tempList.add(message);
//						}
//					}
//					for(int i=list.size()>20?list.size()-20:0;i<list.size();i++){
//						tempList.add( list.get(i));
//					}
				}
				
				final StringBuilder builder = new StringBuilder();
				builder.append("<html><body><table cellpadding=0 cellspacing=0>");

				final TimerTask transcriptTask = new TimerTask() {
					public void run() {
						Date lastPost = null;
						String lastPerson = null;
						boolean initialized = false;
						// TODO
						boolean flag = true;
						int countRow=0;
						for (HistoryMessage message : tempList) {
							countRow=countRow++;

							String value = "["+ messageTimeFormatter.format(message.getDate()) + "]&nbsp;&nbsp;  ";
							// TODO判断
								String color = "blue";
								String from = message.getFrom();
								String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
								String body = org.jivesoftware.spark.util.StringUtils.escapeHTMLTags(message.getBody());
								if (nickname.equals(message.getFrom())) {
									String otherJID = StringUtils.parseBareAddress(message.getFrom());
									String myJID = SparkManager.getSessionManager().getBareAddress();

									if (otherJID.equals(myJID)) {
										nickname = personalNickname;
									} else {
										nickname = StringUtils.parseName(nickname);
									}
								}

								if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) {
									color = "red";
								}

								long lastPostTime = lastPost != null ? lastPost.getTime() : 0;
								int diff = DateUtils.getDaysDiff(lastPostTime,message.getDate().getTime());
//								System.out.println(message.getDate());
								if (diff != 0) {
									if (initialized) {
										builder.append("<tr><td><br></td></tr>");
									}

									builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>")
											.append(notificationDateFormatter.format(message.getDate()))
											.append("</u></b></font></td></tr>");
									lastPerson = null;
									initialized = true;
								}

								// value

								boolean newInsertions = lastPerson == null|| !lastPerson.equals(nickname);

								if (newInsertions) {
									if(!isChinaGroup){
										builder.append("<tr valign=top><td colspan=2 nowrap>");
										builder.append("<font size=4 color='").append(color).append("'><b>");
										builder.append(nickname);
										builder.append("</b></font>");
										builder.append("</td></tr>");
									}
								}

								builder.append("<tr valign=top><td align=left nowrap>");
								if(isChinaGroup){
									builder.append(value+" "+StringUtils.parseResource(message.getFrom())+"：");
								}else{
									builder.append(value);
								}
								builder.append("</td><td align=left>");
								builder.append(body);

								builder.append("</td></tr>");

								lastPost = message.getDate();
								lastPerson = nickname;
						}
						builder.append("</table></body></html>");

						// Handle no history
						if (transcript.getMessages().size() == 0) {
							builder.append("<b>").append(Res.getString("message.no.history.found")).append("</b>");
						}

						window.setText(builder.toString());
						//window.setSelectionStart(window.getText().length());
						messageHistoryPanel.scrollToBottom();
						//
						builder.replace(0, builder.length(), "");
					}
				};

				TaskEngine.getInstance().schedule(transcriptTask, 10);
			}
		};
		transcriptLoader.start();

	}

}
